package ru.minidoc.web.controller;
import java.nio.charset.Charset;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.test.jdbc.SimpleJdbcTestUtils;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class AdminController {
    @Autowired
    private DataSource dataSource;

    @RequestMapping(value = "/admin.action",method = RequestMethod.GET)
    public String admin(ModelMap model){
        return "admin";
    }

    @RequestMapping(value = "/admin/execute.action",method = RequestMethod.POST)
    public String execute(@RequestParam("sql") String sql, ModelMap model){
        EncodedResource resource = new EncodedResource(new ByteArrayResource(sql.getBytes(Charset.forName("utf-8"))), "utf-8");
        SimpleJdbcTestUtils.executeSqlScript(new SimpleJdbcTemplate(dataSource), resource, false);
        return "redirect:/admin.action";
    }
    
}
